﻿using System;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using IronOne.SalesOne.BusinessObjects;

namespace IronOne.SalesOne.SalesOneWeb.UserManagement
{
    public partial class AssignPermissions : SOSecurityPage
    {
        Facade.StructureFacade structureFacade = new Facade.StructureFacade();
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateUserCredentials(Request.Url.LocalPath);

            if (!IsPostBack)
            {
                PopulateRoles(structureFacade.GetAspnetUserRoles(""));
            }
            btnSave.Visible = false;
            //btnSave0.Visible = false;
            grdTasks.Visible = false;
        }

        public void PopulateRoles(List<UserRole_aspnet> userTypes)
        {
            ddlUserRole.DataSource = userTypes;
            ddlUserRole.DataTextField = "RoleName";
            ddlUserRole.DataValueField = "RoleId";
            ddlUserRole.DataBind();

            InsertDDLItems(ddlUserRole, "Select...", 0);
            
        }

        public void PopulateTasks(List<Task> tasks)
        {
            if (tasks.Count > 0)
            {
               
                grdTasks.DataSource = tasks;
                grdTasks.DataBind();

                btnSave.Visible = true;
                //btnSave0.Visible = true;
                grdTasks.Visible = true;
            }
            else
            {
                Response.Write("No tasks found.");
                btnSave.Visible = false;
                //btnSave0.Visible = false;
                grdTasks.Visible = false;
            }
           
        }

        public void InsertDDLItems(DropDownList ddl, string Text, int Position)
        {
            ListItem item = new ListItem(Text, Text);
            ddl.Items.Insert(Position, Text);
            //ddl.Items.Add( item);
        }

        protected void ddlUserRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlUserRole.SelectedIndex > 0)
                PopulateTasks(structureFacade.GetTasksForRole(new Guid(ddlUserRole.SelectedValue)));

            
        }

        public void SetPermissionValues(string permissionString)
        {
           
            //if(permissionString.Contains("C"))//Create
            //    chkCreate.Checked=true;

            //if(permissionString.Contains("E"))//Enquiry
            //    chkEnquiry.Checked=true;

            //if(permissionString.Contains('D'))//delete
            //    chkDelete.Checked=true;

            //if(permissionString.Contains("U"))//update
            //    chkUpdate.Checked=true;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            GetCheckedItems();
            grdTasks.Visible = true;
            btnSave.Visible = true;
            //btnSave0.Visible = true;
            
        }

        protected void ddlTasks_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (ddlTasks.SelectedIndex > 0)
            //{
            //    string permissions = "";

            //    try
            //    {
            //        permissions = structureFacade.GetPermissions(new Guid(ddlUserRole.SelectedValue), Convert.ToInt32(ddlTasks.SelectedValue));
            //    }
            //    catch { permissions = ""; }

            //    if (permissions != null && permissions != "")
            //    {
            //        string[] arrPermissions = permissions.Split(new char[] { '=' });
            //        SetPermissionValues(arrPermissions[1]);
            //    }
            //}
        }

        protected void grdUsers_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //DataRowView rowView = (DataRowView)e.Row.DataItem;
                //sourceDocDS.sourceDocDataRow mainLineRow = (sourceDocDS.sourceDocDataRow)rowView.Row;
                Task task = (Task)e.Row.DataItem;
                CheckBox chkCreate = (CheckBox)e.Row.FindControl("chkCreate");
                CheckBox chkDelete = (CheckBox)e.Row.FindControl("chkDelete");
                CheckBox chkUpdate = (CheckBox)e.Row.FindControl("chkUpdate");
                CheckBox chkEnquiry = (CheckBox)e.Row.FindControl("chkEnquiry");
               

                string permissions = "";

                try
                {
                    permissions = structureFacade.GetPermissions(new Guid(ddlUserRole.SelectedValue), Convert.ToInt32(task.TaskId));
                }
                catch { permissions = ""; }

               
                if (permissions != null && permissions != "")
                {
                    string[] arrPermissions = permissions.Split(new char[] { '=' });
                    string permissionString = arrPermissions[1];

                    if (permissionString.Contains("C"))//Create
                        chkCreate.Checked = true;

                    if (permissionString.Contains("E"))//Enquiry
                        chkEnquiry.Checked = true;

                    if (permissionString.Contains('D'))//delete
                        chkDelete.Checked = true;

                    if (permissionString.Contains("U"))//update
                        chkUpdate.Checked = true;
                }

               

                //switch (mainLineRow.VismaStatus)
                //{
                //    case IVismaStatus.IN_ACTIVE: LblVismaStatus.Text = ""; break;
                //    case IVismaStatus.PENDING: LblVismaStatus.Text = "Pending"; break;
                //    case IVismaStatus.ACCEPTED: LblVismaStatus.Text = "Accepted "; break;
                //    case IVismaStatus.REJECTED: LblVismaStatus.Text = "Rejected"; break;
                //    default: LblVismaStatus.Text = ""; break;
                //}
            }
        }

        protected void grdUsers_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //int[] cols = (int[])Session["hideCols"];
            int[] cols = {4};
            if (cols != null)
            {
                for (int i = 0; i < cols.Length; i++)
                {
                    e.Row.Cells[cols[i]].Visible = false;

                }
            }


        }

        private void GetCheckedItems()
        {
            CheckBox chkCreate ;
            CheckBox chkDelete; 
            CheckBox chkUpdate ;
            CheckBox chkEnquiry ;

            string chkBoxIndex = string.Empty;

            //loop through each row in the GridView

            foreach (GridViewRow row in grdTasks.Rows)
            {
                Task task = (Task)row.DataItem;
                //get the index of the current CheckBox

                chkBoxIndex = row.Cells[5].Text;

                //chk = (CheckBox)row.FindControl(ctrl);
                chkCreate = (CheckBox)row.FindControl("chkCreate");
                chkDelete = (CheckBox)row.FindControl("chkDelete");
                chkUpdate = (CheckBox)row.FindControl("chkUpdate");
                chkEnquiry = (CheckBox)row.FindControl("chkEnquiry");

                //now see if the current CheckBox is checked

                StringBuilder sb = new StringBuilder();

                if (chkCreate.Checked)//create
                    sb.Append("C,");

                if (chkEnquiry.Checked)//enqiury
                    sb.Append("E,");

                if (chkDelete.Checked)//delete
                    sb.Append("D,");

                if (chkUpdate.Checked)//update
                    sb.Append("U,");

                if (sb.Length != 0)
                    sb.Remove(sb.Length - 1, 1).ToString();


                int result = structureFacade.UpdatePermission(new Guid(ddlUserRole.SelectedValue),Convert.ToInt32( row.Cells[4].Text), sb.ToString());

            }

        }



    }
}
